from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from typing import List, Optional
from app import models, schemas

class ScanPathRepository:
    @staticmethod
    async def create_scan_path(db: Session, path: schemas.ScanPathCreate) -> models.ScanPath:
        try:
            db_path = models.ScanPath(**path.dict())
            db.add(db_path)
            db.commit()
            db.refresh(db_path)
            return db_path
        except IntegrityError:
            db.rollback()
            raise ValueError("该路径已存在")

    @staticmethod
    async def get_scan_paths(db: Session, skip: int = 0, limit: int = 100) -> List[models.ScanPath]:
        return db.query(models.ScanPath).offset(skip).limit(limit).all()

    @staticmethod
    async def get_scan_path(db: Session, path_id: int) -> Optional[models.ScanPath]:
        return db.query(models.ScanPath).filter(models.ScanPath.id == path_id).first()

    @staticmethod
    async def update_scan_path(db: Session, path_id: int, path: schemas.ScanPathCreate) -> Optional[models.ScanPath]:
        try:
            db_path = db.query(models.ScanPath).filter(models.ScanPath.id == path_id).first()
            if db_path:
                for key, value in path.dict().items():
                    setattr(db_path, key, value)
                db.commit()
                db.refresh(db_path)
            return db_path
        except IntegrityError:
            db.rollback()
            raise ValueError("该路径已存在")

    @staticmethod
    async def delete_scan_path(db: Session, path_id: int) -> bool:
        db_path = db.query(models.ScanPath).filter(models.ScanPath.id == path_id).first()
        if db_path:
            db.delete(db_path)
            db.commit()
            return True
        return False

    @staticmethod
    async def get_enabled_paths(db: Session) -> List[models.ScanPath]:
        return db.query(models.ScanPath).filter(models.ScanPath.enabled == True).all()
